package com.silverhaze.aurora.launcher.web;

import com.silverhaze.aurora.launcher.data.FileEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * This code is part of Kg.Axion project. Treat it as strictly confidential.
 * Created by Ivan Babanin.
 * Creation date: 4/7/11 3:05 PM
 */
public class WebDownloader {

    public static final int BUFFER_SIZE = 1024;

    public static byte[] load(String webPath) throws IOException {
        URL url = new URL(webPath);

        int readByteSize = 0;
        byte[] buffer = new byte[BUFFER_SIZE];

        InputStream inputStream = url.openStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        while ((readByteSize = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, readByteSize);
        }

        return outputStream.toByteArray();
    }

    public static List<FileEntity> listFileEntities(String webPath) throws IOException {
        byte[] load = load(webPath);
        String fileEntitiesAllString = new String(load);
        List<FileEntity> result = new ArrayList<FileEntity>();
        String[] fileEntitiesString = fileEntitiesAllString.split("\n");

        for (String fileEntityString : fileEntitiesString) {
            String[] partString = fileEntityString.split("\t");

            if (partString.length == 3) {
                result.add(new FileEntity(partString[0], partString[1], Integer.parseInt(partString[2])));
            }
        }

        return result;
    }
}
